"""
请假/加班申请模型
"""
from datetime import datetime
from app import db


class LeaveApplication(db.Model):
    """请假/加班申请表"""
    __tablename__ = 'mx_leave_applications'
    
    id = db.Column(db.Integer, primary_key=True)
    applicant_id = db.Column(db.String(50), db.ForeignKey('mx_employees.employee_id'), nullable=False)
    apply_type = db.Column(db.String(20), nullable=False, comment='申请大类: leave(请假), overtime(加班)')
    leave_type = db.Column(db.String(30), nullable=True, comment='细分请假类型: annual(年假), personal(事假), sick(病假), marriage, funeral, maternity, compensatory, other 等; 加班时可为空')
    leave_days = db.Column(db.Float, nullable=False, comment='天数 (旧字段，逐步废弃，存储=leave_hours/8，精度保留)')
    leave_hours = db.Column(db.Float, nullable=True, comment='时长（小时，可为空；若为空则根据 leave_days*8 推导）')
    # 改为 DateTime 支持到小时级：原有 DATE 字段迁移需执行 SQL
    # MySQL 迁移示例：
    #   ALTER TABLE mx_leave_applications MODIFY start_date DATETIME NOT NULL;
    #   ALTER TABLE mx_leave_applications MODIFY end_date DATETIME NOT NULL;
    start_date = db.Column(db.DateTime, nullable=False, comment='开始时间（支持小时）')
    end_date = db.Column(db.DateTime, nullable=False, comment='结束时间（支持小时）')
    reason = db.Column(db.Text, comment='申请理由')
    status = db.Column(db.String(20), default='pending', comment='状态: pending, approved, rejected')
    project_id = db.Column(db.Integer, nullable=True, comment='所属项目ID，用于成本统计')
    process_instance_id = db.Column(db.String(100), comment='Flowable流程实例ID')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联
    applicant = db.relationship('Employee', backref='leave_applications')
    
    def to_dict(self):
        hours = self.leave_hours if self.leave_hours is not None else (
            self.leave_days * 8 if self.leave_days is not None else None
        )
        return {
            'id': self.id,
            'applicant_id': self.applicant_id,
            'applicant_name': self.applicant.name if self.applicant else None,
            'apply_type': self.apply_type,
            'leave_type': self.leave_type,
            'leave_days': self.leave_days,
            'leave_hours': hours,
            'start_date': self.start_date.isoformat() if self.start_date else None,
            'end_date': self.end_date.isoformat() if self.end_date else None,
            'reason': self.reason,
            'status': self.status,
            'project_id': self.project_id,
            'process_instance_id': self.process_instance_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
